package com.softline.documentsmall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.softline.documentsmall.dao.DictionaryMapper;
import com.softline.documentsmall.dao.EntryDetailMapper;
import com.softline.documentsmall.dao.EntryDetailsLogMapper;
import com.softline.documentsmall.dao.MaintainLogMapper;
import com.softline.documentsmall.entity.*;
import com.softline.documentsmall.ret.ReturnVO;
import com.softline.documentsmall.ret.ReturnVOUtils;
import com.softline.documentsmall.service.EntryDetailLogService;
import com.softline.documentsmall.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author wph
 * @date 2021/01/18 15:27
 */
@Service
@Slf4j
public class EntryDetailsLogServiceImp implements EntryDetailLogService {

    @Autowired
    private EntryDetailsLogMapper EntryDetailsLogMapper;
    @Autowired
    private EntryDetailMapper entryDetailMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private DictionaryServiceImp dictionaryServiceImp;
    @Autowired
    private MaintainLogMapper maintainLogMapper;

    /**
     * 新增日志
     *
     * @param entryDetailsSubmit 条目提交审核详情对象
     * @param approveState       审批状态：0未审批，1审批通过，2审批不通过
     * @param userId
     * @param reason
     */
    @Override
    public void insertDetailsLog(EntryDetailsSubmit entryDetailsSubmit, Integer approveState, String userName, String userId, String reason) {
        EntryDetailsLog entryDetailsLog = new EntryDetailsLog();
        if (!ObjectUtils.isEmpty(entryDetailsSubmit)) {
            int changeNum = 0;
            if (entryDetailsSubmit.getId() != null) {
                entryDetailsLog.setDetailsSubmitId(entryDetailsSubmit.getId());
            }
            if (entryDetailsSubmit.getSubmitId() != null) {
                entryDetailsLog.setSubmitId(entryDetailsSubmit.getSubmitId());
            }
            if (entryDetailsSubmit.getDictionaryId() != null && !"".equals(entryDetailsSubmit.getDictionaryId())) {
                entryDetailsLog.setDictionaryId(entryDetailsSubmit.getDictionaryId());
                Integer changeCount = EntryDetailsLogMapper.selectUpdateCount(entryDetailsSubmit.getDictionaryId(), entryDetailsSubmit.getLanguage());
                entryDetailsLog.setChangeCount(changeCount + 1);
                //根据术语ID查询对象
                Dictionary dictionary = dictionaryMapper.findById(entryDetailsSubmit.getDictionaryId());
                //调用公共方法查询对应术语名字
                String name = dictionaryServiceImp.selectName(entryDetailsSubmit.getLanguage(), dictionary);
                entryDetailsLog.setName(name);
            }
            if (entryDetailsSubmit.getLanguage() != null && !"".equals(entryDetailsSubmit.getLanguage())) {
                entryDetailsLog.setLanguage(entryDetailsSubmit.getLanguage());
                entryDetailsLog.setDate(getNowTime(entryDetailsSubmit.getLanguage()));
            }
            EntryDetails byDictionaryIdLanguageTitle = entryDetailMapper.findByDictionaryIdLanguageTitleSort(entryDetailsSubmit.getDictionaryId(), entryDetailsSubmit.getLanguage(), entryDetailsSubmit.getSort());
            if (!ObjectUtils.isEmpty(byDictionaryIdLanguageTitle)) {
                entryDetailsLog.setOldTitle(byDictionaryIdLanguageTitle.getTitle());
                entryDetailsLog.setOldContent(byDictionaryIdLanguageTitle.getContent());
            }
            if (entryDetailsSubmit.getTitle() != null && !"".equals(entryDetailsSubmit.getTitle())) {
                entryDetailsLog.setNewTitle(entryDetailsSubmit.getTitle());
            }
            if (entryDetailsSubmit.getContent() != null && !"".equals(entryDetailsSubmit.getContent())) {
                entryDetailsLog.setNewContent(entryDetailsSubmit.getContent());
            }
            //计算新老区块名称字符串差值
            if (entryDetailsLog.getOldTitle() != null && entryDetailsLog.getNewTitle() != null) {
                changeNum = entryDetailsLog.getNewTitle().length() - entryDetailsLog.getOldTitle().length();
            }
            //计算区块具体内容字符串差值
            if (entryDetailsLog.getOldContent() != null && entryDetailsLog.getNewContent() != null) {
                changeNum = entryDetailsLog.getOldContent().length() - entryDetailsLog.getNewContent().length();
            }
            entryDetailsLog.setChangeNum(changeNum);
            //更改理由暂时没想好怎么填写 TODO:后期增加更改理由,看是数据字典还是直接传输字符
//            entryDetailsLog.setReason();
            entryDetailsLog.setIsCreate(approveState);
            entryDetailsLog.setIsCreate(approveState);
            entryDetailsLog.setUpdateUser(userName);
            entryDetailsLog.setUpdateId(userId);
            entryDetailsLog.setReason(reason);

            int insertResult = EntryDetailsLogMapper.insert(entryDetailsLog);
            log.info("新增审核日志  " + (insertResult == 1 ? "成功" : "失败") + "  " + entryDetailsLog.toString());
        }
    }

    @Override
    public ReturnVO getDetailsLogList(PageQueryVO pageQuery) {
        String type = pageQuery.getType();
        Long count = EntryDetailsLogMapper.selectCount(type);
        JSONObject jsonObject = new JSONObject();
        Integer page = pageQuery.getPage();
        Integer size = pageQuery.getSize();
        jsonObject.put("page", page);
        jsonObject.put("size", size);
        List obj = heardFour(pageQuery);
        jsonObject.put("counts", obj);
        List<EntryDetailsLog> listEntryDetailsLog = EntryDetailsLogMapper.findByParams(size * (page - 1), size, type);
        jsonObject.put("dataList", listEntryDetailsLog);
        jsonObject.put("totals", count);
        return ReturnVOUtils.success(jsonObject);
    }

    private List heardFour(PageQueryVO pageQuery) {
        String type = pageQuery.getType();
        Long count = EntryDetailsLogMapper.selectCount(type);
        List obj = new ArrayList();
        obj.add(count);
        List<Long> countList = maintainLogMapper.selectMaintainLogListCount();
        if (countList != null && countList.size() > 0) {
            for (Long aLong : countList) {
                obj.add(aLong);
            }
        } else {
            obj.add(0);
            obj.add(0);
            obj.add(0);
            obj.add(0);
        }
        return obj;
    }

    @Override
    public ReturnVO getVindicateList(PageQueryVO pageQuery) {
        ReturnVO detailsLogList = new ReturnVO();
        // 1:术语库,2:语音库,3:语料库,4:知识库      3和4目前没有,不返回数据
        if (pageQuery.getGenre() == 1) {
            detailsLogList = this.getDetailsLogList(pageQuery);
            return detailsLogList;
        } else {
            JSONObject jsonObject = new JSONObject();
            Integer page = pageQuery.getPage();
            Integer size = pageQuery.getSize();
            jsonObject.put("page", page);
            jsonObject.put("size", size);
            Integer genre = pageQuery.getGenre();
            List<MaintainLog> maintainLogs = maintainLogMapper.selectMaintainLogList(genre, (page - 1) * size, size);
            if (maintainLogs != null && maintainLogs.size() > 0) {
//                for (MaintainLog maintainLog : maintainLogs) {
//                    maintainLog.setTempDate(DateUtils.dateTo(maintainLog.getDate()));
//                    System.out.println("maintainLog 临时时间= " + maintainLog.getTempDate());
//                }
            }
            List obj = heardFour(pageQuery);
            Long count = maintainLogMapper.selectMaintainLogCount(pageQuery.getGenre());
            jsonObject.put("counts", obj);
            jsonObject.put("dataList", maintainLogs);
            jsonObject.put("totals", count);
            return ReturnVOUtils.success(jsonObject);
        }
    }

    public String getNowTime(String language) {
        String time = "";
        if ("cn".equals(language)) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 (E)  HH:mm:ss");//设置日期格式
            time = df.format(new Date());
        } else {
            SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss 'CST' yyyy", Locale.ENGLISH);
            time = dateFormat.format(new Date());
        }
        return time;
    }
}
